//
//  GuaziAppDelegate.m
//  Guazi
//
//  Created by koolearn on 11-4-17.
//  Copyright __MyCompanyName__ 2011. All rights reserved.
//

#import "GuaziAppDelegate.h"
#import "DBConnection.h"
#import "CommonDAO.h"
#import "ColorUtils.h"
#import "ImageStore.h"
#import "TwitterClient.h"
#import "URLStore.h"
#import "FriendsTimelineController.h"
#import "UserTimelineController.h"
#import "FavoritesViewController.h"
#import "REString.h"
#import "LinkViewController.h"
#import "WebViewController.h"

#import "FriendsViewController.h"
#import "SilenceFolloweeViewController.h"
#import "FollowersViewController.h"
#import "LocationViewController.h"
#import "DirectMessage.h"
#import "FriendListViewController.h"
#import "SilenceFolloweeViewController.h"
#import "NetworkUtil.h"
#import "RegisterViewController.h"
#import "ActivateViewController.h"
#import "DMTimelineController.h"
#import "PreferencesViewController.h"
#import "DataUploadService.h"


@interface NSObject (GuaziAppDelegate)
- (void) didLeaveTab:(UINavigationController*)navigationController;
- (void) didSelectTab:(UINavigationController*)navigationController;
- (void) updateFavorite:(Status*)status;
- (void) toggleFavorite:(BOOL)favorited status:(Status*)status;
- (BOOL) isRoot;
@end


@interface GuaziAppDelegate(private)
- (void)initializeUserDefaults;
- (void) addSegmentControl:(UIViewController*)controller type:(NSInteger)type selectedIndex:(NSInteger)selectedIndex;
- (NSInteger) findTweetViewController:(NSInteger)index;
- (UIViewController*) createTweetViewController:(NSInteger)index;
- (void) clearUserData;
- (void)autoRefresh:(NSTimer*)timer;
- (void)setNextTimer:(NSTimeInterval)interval;
@end



@implementation GuaziAppDelegate

@synthesize window;
@synthesize tabBarController;
@synthesize selectedTab;

@synthesize imageStore;
@synthesize user;
@synthesize isValidateUser;

@synthesize postView;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    [self initializeUserDefaults];
	
 	BOOL forceCreate = [[NSUserDefaults standardUserDefaults] boolForKey:@"clearLocalCache"];
	forceCreate = YES;
    [DBConnection createEditableCopyOfDatabaseIfNeeded:forceCreate];
    [DBConnection getDatabase];
    [[NSUserDefaults standardUserDefaults] setBool:false forKey:@"clearLocalCache"];
    
    //得到当前登录用户
    User* owner = [User currentAccountUser];
    if ( owner == nil ) {
        //没有注册，先在本地生成用户记录
        owner = [User userWithLocal];
        [owner updateDB:YES withName:YES withAccount:YES];
    }
    
    //owner.name = @"guazi.me@gmail.com";
    //owner.password = @"111111";
    //owner.state = @"VALID";
    //owner.userId = 64976183141;
    
    NSString *username = owner.name;
    NSString *password = owner.password;
    [[NSUserDefaults standardUserDefaults] setObject:username forKey:@"username"];
    [[NSUserDefaults standardUserDefaults] setObject:password forKey:@"password"];
    
    NSString *versionStr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    [[NSUserDefaults standardUserDefaults] setObject:versionStr forKey:@"appVersion"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.user = owner;
    self.isValidateUser = YES;
    
    BOOL networkAvailable = [NetworkUtil isbroadbandAvailable];
    if ( networkAvailable ) {
        if ( [kUserStateLocal compare:owner.state]!=NSOrderedSame && [kUserStateLocked compare:owner.state]!=NSOrderedSame ) {
            User* u = [TwitterClient verifyAccount];
            if ( u ) {
                //认证通过
                owner = u;
            }
            else {
                //认证不通过
                self.isValidateUser = NO;
            }
        }
    }
    
	
    [UIColor initTwitterFonColorScheme];
    imageStore = [[ImageStore alloc] init];
    
    selectedTab = 0;
	
	//通讯录
	//[self addSegmentControl:0 selectedIndex:0];
	
	//动态
	UINavigationController* nav = [tabBarController.viewControllers objectAtIndex:1];
	FriendsTimelineController* timelineController = (FriendsTimelineController*) nav.topViewController;
	timelineController.tweetType = 0;//friends tweet
    timelineController.isRoot = YES;
	[self addSegmentControl:timelineController type:1 selectedIndex:0];
	
    tabBarController.selectedIndex = 0;
	
  	[window addSubview:tabBarController.view];
    
    // Add the tab bar controller's view to the window and display.
    [window addSubview:tabBarController.view];
    [window makeKeyAndVisible];

    int interval = [[NSUserDefaults standardUserDefaults] integerForKey:@"autoRefresh"];
    autoRefreshInterval = 0;
    if (interval > 0) {
        autoRefreshInterval = interval * 60;
        if (autoRefreshInterval < 180) autoRefreshInterval = 180;
        [self setNextTimer:autoRefreshInterval];
    }
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
    if (autoRefreshTimer) {
        [autoRefreshTimer invalidate];
        autoRefreshTimer = nil;
    }
    
    //if (postView != nil) {
    //    [self.postView saveTweet];
    //}
}



- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}


#pragma mark -
#pragma mark UITabBarControllerDelegate methods


//
// UITabBarControllerDelegate
//
- (void)tabBarController:(UITabBarController *)tabBar didSelectViewController:(UIViewController *)viewController
{
    UINavigationController* nav = [self.tabBarController.viewControllers objectAtIndex:selectedTab];    
    UIViewController *c = [nav.viewControllers objectAtIndex:0];
    if ([c respondsToSelector:@selector(didLeaveTab:)]) {
        [c didLeaveTab:nav];
    }
    
    selectedTab = tabBar.selectedIndex;
    
    nav = (UINavigationController*)[tabBarController.viewControllers objectAtIndex:selectedTab];
    c = [nav.viewControllers objectAtIndex:0];
    if ([c respondsToSelector:@selector(didSelectTab:)]) {
        [c didSelectTab:nav];
    }
}


/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
}
*/


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
	[imageStore didReceiveMemoryWarning];
}


- (void)dealloc {
	[webView release];
	[imageStore release];
    [tabBarController release];
    [window release];
    [super dealloc];
}


- (void)initializeUserDefaults
{
    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"",                             @"username",
                         @"",                             @"password",
						 @"",							  @"screenName",
                         [NSNumber numberWithBool:false], @"clearLocalCache",
                         [NSNumber numberWithBool:true],  @"loadAllTabOnLaunch",
                         [NSNumber numberWithBool:true],  @"autoScrollToFirstUnread",
                         [NSNumber numberWithInt:5],      @"autoRefresh",
                         @"",                             @"tweet",
                         [NSNumber numberWithLongLong:0], @"inReplyToStatusId",
                         @"",                             @"to",
                         @"",                             @"recipient",
                         [NSNumber numberWithInt:2],      @"searchDistance",
                         [NSNumber numberWithInt:50],     @"launchCount",
                         [NSNumber numberWithInt:13],     @"fontSize",
                         nil];
	
    for (id key in dic) {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:key] == nil) {
            [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:key] forKey:key];
        }
    }
}


+ (void)openAccountView:(UIViewController*)controller
{
    AccountViewController* accountView = [[[AccountViewController alloc] initWithNibName:@"AccountView" bundle:nil] autorelease];
	UINavigationController* parentController = [[UINavigationController alloc] initWithRootViewController:accountView];
	[controller.navigationController presentModalViewController:parentController animated:YES];
	[parentController release];
}


+ (void) openRegisterView:(UIViewController*)controller
{
    User* user = [GuaziAppDelegate getAppDelegate].user;
    
    if ( [kUserStateLocal compare:user.state] == NSOrderedSame ) {
        RegisterViewController* registerController = [[RegisterViewController alloc] initWithStyle:UITableViewStyleGrouped];
        UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:registerController];
        [controller.navigationController presentModalViewController:nav animated:YES];
        [registerController release];
        [nav release];
    }
    else if ( [kUserStateUnopen compare:user.state] == NSOrderedSame ) {
        ActivateViewController* activateController = [[ActivateViewController alloc] initWithStyle:UITableViewStyleGrouped];
        UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:activateController];
        [controller.navigationController presentModalViewController:nav animated:YES];
        [activateController release];
        [nav release];
    }
    else  {
        //[GuaziAppDelegate openAccountView:controller];
    }
}


- (PostViewController*)postView
{
    if (postView == nil) {
        postView = [[PostViewController alloc] initWithNibName:@"PostView" bundle:nil];
		CGPoint center = postView.view.center;
		center.y = center.y + 20;
		postView.view.center = center;
		
    }

	NSInteger currTab = [tabBarController selectedIndex];
    postView.navigation = (UINavigationController*)[tabBarController.viewControllers objectAtIndex:currTab];
	
    return postView;
}


- (void) post: (id) sender
{
    if (tabBarController.selectedIndex == GUAZI_TAB_MESSAGES) {
        [self.postView editDirectMessage:nil];
    }
    else {
        [self.postView post];
    }
}


- (void)postTweetDidSucceed:(NSDictionary*)dic
{
    UINavigationController* nav = (UINavigationController*)[tabBarController.viewControllers objectAtIndex:GUAZI_TAB_TWEETS];
    Status *status = [Status statusWithJsonDictionary:dic type:TWEET_TYPE_FRIENDS];
    [status insertDB];
    FriendsTimelineController *c = (FriendsTimelineController*)[nav.viewControllers objectAtIndex:0];
    [c postTweetDidSucceed:status];
}


- (void)postViewAnimationDidFinish:(BOOL)isDirectMessage
{
    UINavigationController *nav = nil;
	NSInteger currTab = tabBarController.selectedIndex;
    if (isDirectMessage == false && currTab == GUAZI_TAB_TWEETS ) {
        nav = (UINavigationController*)[tabBarController.viewControllers objectAtIndex:GUAZI_TAB_TWEETS];    
    }        
    else if (isDirectMessage && currTab == GUAZI_TAB_MESSAGES) {
        nav = (UINavigationController*)[tabBarController.viewControllers objectAtIndex:GUAZI_TAB_MESSAGES];    
    }
	
    UIViewController *c = nav.topViewController;
    if ([c respondsToSelector:@selector(postViewAnimationDidFinish)]) {
        [c performSelector:@selector(postViewAnimationDidFinish)];
    }
}


- (void)sendMessageDidSucceed:(NSDictionary*)dic
{
    UINavigationController* nav = (UINavigationController*)[tabBarController.viewControllers objectAtIndex:2];
    DirectMessage *dm = [DirectMessage messageWithJsonDictionary:dic];
    [dm insertDB];
    UIViewController *c = nav.topViewController;
    if ([c respondsToSelector:@selector(sendMessageDidSucceed:)]) {
        [c performSelector:@selector(sendMessageDidSucceed:) withObject:dm];
    }
}


//
// Bypass message deletion and toggle favorite completed
//
- (void)tweetDidDelete:(TwitterClient*)client obj:(NSObject*)obj
{
	
    Status* sts = (Status*)client.context;
	
    if (client.hasError) {
        if (client.statusCode == 404) {
            [sts deleteFromDB];
        }
        else {
            [client alert];
        }
    }
    else if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary*)obj;
        sqlite_int64 statusId = [[dic objectForKey:@"id"] longLongValue];        
        if (sts.statusId == statusId) {
            [sts deleteFromDB];
        }
    }
	else {
		//ggua删除微博，没有返回值
		[sts deleteFromDB];
	}
    [sts release];
}


+ (BOOL)isMyScreenName:(NSString*)screen_name
{
    GuaziAppDelegate *delegate = [GuaziAppDelegate getAppDelegate];
    return ([delegate.user.screenName caseInsensitiveCompare:screen_name] == NSOrderedSame) ? true : false;
}


+(GuaziAppDelegate*)getAppDelegate
{
    return (GuaziAppDelegate*)[UIApplication sharedApplication].delegate;
}




+ (void) showAlert:(NSString*)message
{
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示" 
														message:message 
													   delegate:nil 
											  cancelButtonTitle:@"确定" 
											  otherButtonTitles:nil];
	[alertView show];
	[alertView release];
}


+ (void) showAlert:(NSString*)title message:(NSString*)message
{
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title 
														message:message 
													   delegate:nil 
											  cancelButtonTitle:@"确定" 
											  otherButtonTitles:nil];
	[alertView show];
	[alertView release];
}


- (void)toggleFavorite:(Status*)status
{
    TwitterClient *client = [[TwitterClient alloc] initWithTarget:self action:@selector(favoriteDidChange:obj:)];
    client.context = [status  retain];
    [client toggleFavorite:status];
}


- (void)favoriteDidChange:(TwitterClient*)sender obj:(NSObject*)obj
{
    Status* sts = sender.context;
    
    if (sender.hasError) {
        if (sender.statusCode == 404 || sender.statusCode == 403) {
            BOOL favorited = (sender.request == TWITTER_REQUEST_FAVORITE) ? true : false;
            sts.favorited = favorited;
            [sts updateFavoriteState];
        }
        else {
            [sender alert];
        }
    }
    else if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary*)obj;
        sqlite_int64 statusId = 0;
		BOOL favorited = (sender.request == TWITTER_REQUEST_FAVORITE) ? true : false;
		if (favorited) {
			NSDictionary* weibo = [dic objectForKey:@"openAPIWeibo"];
			statusId = [[weibo objectForKey:@"id"] longLongValue];
		}
		else {
			statusId = [[dic objectForKey:@"favoritesIds"] longLongValue];
		}
		
        if (sts.statusId == statusId) {
            sts.favorited = favorited;
            [sts updateFavoriteState];
        }
    }
	else {
		//TODO: 没有返回值？
		BOOL favorited = (sender.request == TWITTER_REQUEST_FAVORITE) ? true : false;
		sts.favorited = favorited;
		[sts updateFavoriteState];
	}
    
	NSInteger currTab = self.tabBarController.selectedIndex;
    UINavigationController* nav = (UINavigationController*)[tabBarController.viewControllers objectAtIndex:currTab];
    UIViewController *c = nav.topViewController;
    if ([c respondsToSelector:@selector(toggleFavorite:status:)]) {
        //[c performSelector:@selector(toggleFavorite) withObject:sts.favorited withObject:sts];
        [c toggleFavorite:sts.favorited status:sts];
    }
	
    c = [nav.viewControllers objectAtIndex:0];
    if ([c respondsToSelector:@selector(updateFavorite:)]) {
        [c updateFavorite:sts];
    }
	
    // Add/remove from favorites tab
	//TODO: 更新收藏？
    if (currTab != TAB_FAVORITES) {
        nav = (UINavigationController*)[tabBarController.viewControllers objectAtIndex:TAB_FAVORITES];
        c = [nav.viewControllers objectAtIndex:0];
        if ([c respondsToSelector:@selector(updateFavorite:)]) {
            [c updateFavorite:sts];
        }
    }
    [sts release];
}

//
// Handling links
//
static NSString *urlRegexp  = @"(((http(s?))\\:\\/\\/)([-0-9a-zA-Z]+\\.)+[a-zA-Z]{2,6}(\\:[0-9]+)?(\\/[-0-9a-zA-Z_#!:.?+=&%@~*\\';,/$]*)?)";
static NSString *endRegexp  = @"[.,;:]$";
static NSString *nameRegexp = @"(@[0-9a-zA-Z_]+)";
static NSString *hashRegexp = @"(#[-a-zA-Z0-9_.+:=]+)";

- (void)openLinksViewController:(NSString*)text
{
	NSInteger currTab = tabBarController.selectedIndex;
    UINavigationController* nav = (UINavigationController*)[tabBarController.viewControllers objectAtIndex:currTab];
    
    BOOL hasHash = false;
    
    NSMutableArray *links = [NSMutableArray array];
    
    NSMutableArray *array = [NSMutableArray array];
    NSString *tmp = text;
	
    // Find URLs
    while ([tmp matches:urlRegexp withSubstring:array]) {
        NSString *url = [array objectAtIndex:0];
        [array removeAllObjects];
        if ([url matches:endRegexp withSubstring:array]) {
            url = [url substringToIndex:[url length] - 1];
        }
        [links addObject:url];
        NSRange r = [tmp rangeOfString:url];
        tmp = [tmp substringFromIndex:r.location + r.length];
        [array removeAllObjects];
    }
	
    // Find screen names
    tmp = text;
    while ([tmp matches:nameRegexp withSubstring:array]) {
        NSString *username = [array objectAtIndex:0];
        [links addObject:username];
        NSRange r = [tmp rangeOfString:username];
        tmp = [tmp substringFromIndex:r.location + r.length];
        [array removeAllObjects];
    }
	
    // Find hashtags
    tmp = text;
    while ([tmp matches:hashRegexp withSubstring:array]) {
        NSString *hash = [array objectAtIndex:0];
        [links addObject:hash];
        NSRange r = [tmp rangeOfString:hash];
        tmp = [tmp substringFromIndex:r.location + r.length];
        [array removeAllObjects];
        hasHash = true;
    }
	
    if ([links count] == 1) {
        NSString* url = [links objectAtIndex:0];
        NSRange r = [url rangeOfString:@"http://"];
        if (r.location != NSNotFound) {
            [self openWebView:url on:nav];
        }
        else {
            if (hasHash) {
                [self search:[links objectAtIndex:0]];
            }
            else {
                UserTimelineController *userTimeline = [[[UserTimelineController alloc] init] autorelease];
                NSString *aScreenName = [links objectAtIndex:0];
                [userTimeline loadUserTimeline:[aScreenName substringFromIndex:1]];
                [nav pushViewController:userTimeline animated:true];
            }
        }
    }
    else {
        //nav.navigationBar.tintColor = nil;
        
        LinkViewController* linkView = [[[LinkViewController alloc] init] autorelease];
        linkView.links   = links;
        [nav pushViewController:linkView animated:true];
    }
}


- (void)openWebView:(NSString*)url on:(UINavigationController*)nav
{
    if (webView == nil) {
        webView = [[WebViewController alloc] initWithNibName:@"WebView" bundle:nil];
    }
    webView.hidesBottomBarWhenPushed = YES;
    [webView setUrl:url];
    [nav pushViewController:webView animated:YES];
}


- (void)openWebView:(NSString*)url
{
    if (webView == nil) {
        webView = [[WebViewController alloc] initWithNibName:@"WebView" bundle:nil];
    }
    webView.hidesBottomBarWhenPushed = YES;
    [webView setUrl:url];
	
	NSInteger currTab = tabBarController.selectedIndex;
    UINavigationController* nav = (UINavigationController*)[tabBarController.viewControllers objectAtIndex:currTab];
    [nav pushViewController:webView animated:YES];
}


#pragma mark - autoRefresh

- (void)setNextTimer:(NSTimeInterval)interval
{
    autoRefreshTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(timerTask:) userInfo:nil repeats:false];    
}


- (void) timerTask:(NSTimer*)timer
{
    [[DataUploadService sharedInstance] run];
    [self autoRefresh:timer];
}


- (void)autoRefresh:(NSTimer*)timer
{
    [lastRefreshDate release];
    lastRefreshDate = [[NSDate date] retain];
    
    NSArray *views = tabBarController.viewControllers;
    for (int i = 0; i < [views count]; ++i) {
        UINavigationController* nav = (UINavigationController*)[views objectAtIndex:i];
        if ( i == 1 ) {
            //动态
            NSArray* viewControllers = nav.viewControllers;
            for ( UIViewController* c in viewControllers ) {
                if ( [c respondsToSelector:@selector(isRoot)] && [c respondsToSelector:@selector(autoRefresh)]) {
                    BOOL isRoot = [c isRoot];
                    if ( isRoot ) {
                        [c performSelector:@selector(autoRefresh)];
                    }
                }
            }
        }
        else {
            UIViewController *c = [nav.viewControllers objectAtIndex:0];
            if ([c respondsToSelector:@selector(autoRefresh)]) {
                [c performSelector:@selector(autoRefresh)];
            }
        }
    }
    
    [self setNextTimer:autoRefreshInterval];
}



#pragma mark - SegmentControl切换的方法

- (void) addSegmentControl:(UIViewController*)controller type:(NSInteger)type selectedIndex:(NSInteger)selectedIndex
{
	NSArray* barItems = nil;
	SEL action = nil;
	
	if ( type == 0 ) {
		barItems = [NSArray arrayWithObjects:@"通讯录",@"默默",@"粉丝",@"临时", @"附近",nil];
		action = @selector(friendSegmentChanged:);
	}
	else if ( type == 1 ) {
		barItems = [NSArray arrayWithObjects:@"好友",@"@me",@"收藏",@"我的",nil];
		action = @selector(tweetSegmentChanged:);
	}
	
	UISegmentedControl* segment = [[UISegmentedControl alloc] initWithItems:barItems];
	segment.segmentedControlStyle = UISegmentedControlStyleBar;
	if ( selectedIndex >=0 ) segment.selectedSegmentIndex = selectedIndex;
	
	controller.navigationItem.titleView = segment;
	[segment addTarget:self action:action forControlEvents:UIControlEventValueChanged];
	[segment release];
}


/*
 - (void) tweetSegmentChanged:(id)sender
 {
 UISegmentedControl* segment = (UISegmentedControl*)sender;
 NSInteger selectedIndex = segment.selectedSegmentIndex;
 
 UIViewController* controller = nil;
 
 if ( selectedIndex == 0 ) {
 //好友动态
 FriendsTimelineController* friendsTimelineController = [[FriendsTimelineController alloc] init];
 friendsTimelineController.tweetType = 0;//friends tweet
 controller = friendsTimelineController;
 }
 else if ( selectedIndex == 1 ) {
 //@me
 FriendsTimelineController* friendsTimelineController = [[FriendsTimelineController alloc] init];
 friendsTimelineController.tweetType = 1;//friends tweet
 controller = friendsTimelineController;
 }
 else if ( selectedIndex == 2 ) {
 //favorites
 FavoritesViewController *favoritesController = [[FavoritesViewController alloc] initWithNibName:@"FavoritesView" bundle:nil];
 controller = favoritesController;
 }
 else if ( selectedIndex == 3 ) {
 //owner timeline
 UserTimelineController* userTimelineController = [[UserTimelineController alloc] init];
 [userTimelineController setUser:user];
 controller = userTimelineController;	
 }
 
 NSMutableArray* controllerArray = [NSMutableArray array];
 [controllerArray addObject:controller];
 
 UINavigationController* nav = [tabBarController.viewControllers objectAtIndex:1];
 [nav setViewControllers:controllerArray];
 
 [self addSegmentControl:1 selectedIndex:selectedIndex];
 [controller release];
 }
 */


- (void) tweetSegmentChanged:(id)sender
{
	UISegmentedControl* segment = (UISegmentedControl*)sender;
	NSInteger selectedIndex = segment.selectedSegmentIndex;
	
	UINavigationController* nav = [tabBarController.viewControllers objectAtIndex:1];
    NSArray* viewControllers = nav.viewControllers;
    
    NSInteger index = [self findTweetViewController:selectedIndex];
    if ( index == [viewControllers count] - 1 ) return;
    
    NSMutableArray* controllerList = [NSMutableArray arrayWithCapacity:[viewControllers count]];
    for ( int i=0; i<[viewControllers count]; i++ ) {
        if ( i!=index ) {
            [controllerList addObject:[viewControllers objectAtIndex:i]];
        }
    }
    
    if ( index >= 0 ) {
        [controllerList addObject:[viewControllers objectAtIndex:index]];
    }
    else {
        UIViewController* controller = [self createTweetViewController:selectedIndex];
        [controllerList addObject:controller];
    }
    
    [nav setViewControllers:controllerList];
}



- (NSInteger) findTweetViewController:(NSInteger)index
{
	UINavigationController* nav = [tabBarController.viewControllers objectAtIndex:1];
    NSArray* viewControllers = nav.viewControllers;
    if ( viewControllers && [viewControllers count] > 0 ) {
        for ( int i = 0; i<[viewControllers count]; i++ ) {
            UIViewController* c = [viewControllers objectAtIndex:i];
            
            if ( index == 0 ) {
                if ( [c isKindOfClass:[FriendsTimelineController class]] ) {
                    FriendsTimelineController* timelineController = (FriendsTimelineController*) c;
                    if ( timelineController.tweetType == 0 ) {
                        return i;
                    }
                }
            }
            else if ( index == 1 ) {
                if ( [c isKindOfClass:[FriendsTimelineController class]] ) {
                    FriendsTimelineController* timelineController = (FriendsTimelineController*) c;
                    if ( timelineController.tweetType == 1 ) {
                        return i;
                    }
                }
            }
            else if ( index == 2 ) {
                if ( [c isKindOfClass:[FavoritesViewController class]] ) {
                    return i;
                }
            }
            else if ( index == 3 ) {
                if ( [c isKindOfClass:[UserTimelineController class]] ) {
                    //UserTimelineController* timelineController = (UserTimelineController*) c;
                    //if ( timelineController.user == 1 ) {
                    return i;
                    //}
                }
            }
        }
    }
    
    return -1;
}


- (UIViewController*) createTweetViewController:(NSInteger)index
{
    UIViewController* controller = nil;
	if ( index == 0 ) {
		//好友动态
		FriendsTimelineController* friendsTimelineController = [[FriendsTimelineController alloc] init];
		friendsTimelineController.tweetType = 0;//friends tweet
        friendsTimelineController.isRoot = YES;
		controller = friendsTimelineController;
	}
	else if ( index == 1 ) {
		//@me
		FriendsTimelineController* friendsTimelineController = [[FriendsTimelineController alloc] init];
		friendsTimelineController.tweetType = 1;//friends tweet
        friendsTimelineController.isRoot = YES;
		controller = friendsTimelineController;
	}
	else if ( index == 2 ) {
		//favorites
		FavoritesViewController *favoritesController = [[FavoritesViewController alloc] initWithNibName:@"FavoritesView" bundle:nil];
        favoritesController.isRoot = YES;
		controller = favoritesController;
	}
	else if ( index == 3 ) {
		//owner timeline
		UserTimelineController* userTimelineController = [[UserTimelineController alloc] initWithUser:user];
        userTimelineController.isRoot = YES;
		controller = userTimelineController;	
	}
    
    [self addSegmentControl:controller type:1 selectedIndex:index];
    
    return controller;
}


- (void) friendSegmentChanged:(id)sender
{
	UISegmentedControl* segment = (UISegmentedControl*)sender;
	NSInteger selectedIndex = segment.selectedSegmentIndex;
	
	UIViewController* controller = nil;
	
	if ( selectedIndex == 0 ) {
		//通讯录
		FriendsViewController* contactViewController = [[FriendsViewController alloc] init];
		controller = contactViewController;
	}
	else if ( selectedIndex == 1 ) {
		//默默关注
		SilenceFolloweeViewController* followeeViewController = [[SilenceFolloweeViewController alloc] init];
		controller = followeeViewController;
	}
	else if ( selectedIndex == 2 ) {
		//粉丝
		//FollowersViewController* followerViewController = [[FollowersViewController alloc] init];
		//controller = followerViewController;
		FriendListViewController *friends = [[FriendListViewController alloc] initWithUser:user isFollowers:YES];
		controller = friends;
	}
	else if ( selectedIndex == 3 ) {
		//附近的人
		LocationViewController* locationViewController = [[LocationViewController alloc] init];
		controller = locationViewController;	
	}
	else if ( selectedIndex == 4 ) {
		//附近的人
		LocationViewController* locationViewController = [[LocationViewController alloc] init];
		controller = locationViewController;	
	}
	
    NSMutableArray* controllerArray = [NSMutableArray array];
    [controllerArray addObject:controller];
	
	UINavigationController* nav = [tabBarController.viewControllers objectAtIndex:0];
	[nav setViewControllers:controllerArray];
	
	//[self addSegmentControl:0 selectedIndex:selectedIndex];
	[controller release];
}


#pragma mark - 获取ViewController的方法

- (UIViewController*) currentViewController
{
    UINavigationController* nav = [self.tabBarController.viewControllers objectAtIndex:self.tabBarController.selectedIndex];
    UIViewController* controller = [nav topViewController];
    return controller;
}


- (UINavigationController*) currentNavigationController
{
    UINavigationController* nav = [self.tabBarController.viewControllers objectAtIndex:self.tabBarController.selectedIndex];
    return nav;
}


- (UIViewController*) currentTabRootViewController
{
    UINavigationController* nav = [self.tabBarController.viewControllers objectAtIndex:self.tabBarController.selectedIndex];
    return [nav.viewControllers objectAtIndex:0];    
}


- (FriendsViewController*) friendsViewController
{
    UINavigationController* nav = [self.tabBarController.viewControllers objectAtIndex:0];
    for ( UIViewController* controller in nav.viewControllers ) {
        if ( [controller isKindOfClass:[FriendsViewController class]]) {
            return (FriendsViewController*) controller;
        }
    }
    return nil;    
}


- (MyCardsViewController*) myCardsViewController
{
    UINavigationController* nav = [self.tabBarController.viewControllers objectAtIndex:3];
    for ( UIViewController* controller in nav.viewControllers ) {
        if ( [controller isKindOfClass:[MyCardsViewController class]]) {
            return (MyCardsViewController*) controller;
        }
    }
    return nil;    
}


- (SilenceFolloweeViewController*) silenceViewController
{
    UINavigationController* nav = [self.tabBarController.viewControllers objectAtIndex:0];
    for ( UIViewController* controller in nav.viewControllers ) {
        if ( [controller isKindOfClass:[FriendsViewController class]]) {
            return (SilenceFolloweeViewController*) controller;
        }
    }
    return nil;    
}


#pragma mark - 当前用户相关的方法

- (BOOL) isAccountRegistered
{
    if ( [kUserStateLocal compare:user.state] != NSOrderedSame ) return YES;
    else return NO;
}


- (BOOL) isAccountOpened
{
    if ( [kUserStateValid compare:user.state] == NSOrderedSame ) return YES;
    else return NO;
}


- (void) switchUser:(User*)newUser
{
    //保存新用户数据
    newUser.accountFlag = kUserAccountAccountCurrent;
    newUser.relation = kUserRelationSelf;
    [newUser updateDB:YES withName:YES withAccount:YES];

	NSUserDefaults* userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:newUser.name forKey:kKeyUserName];
    [userDefault setObject:newUser.password forKey:kKeyPassword];
    [userDefault synchronize];
    
    //更新老用户数据
    User* oldUser = self.user;
    if ( oldUser.userId == newUser.userId ) {
        [GuaziAppDelegate getAppDelegate].user = newUser;
        return;
    }
    
    oldUser.accountFlag = kUserAccountAccount;
    [oldUser updateDB:NO withName:NO withAccount:YES];
    [GuaziAppDelegate getAppDelegate].user = newUser;

    //清除数据
    [self clearUserData];
    
    //处理通讯录
    UINavigationController* nav = [self.tabBarController.viewControllers objectAtIndex:0];
    [nav popToRootViewControllerAnimated:NO];
    
    UIViewController* controller = [nav.viewControllers objectAtIndex:0];
    if ( [controller isKindOfClass:[FriendsViewController class]] ) {
        FriendsViewController* friendsController = (FriendsViewController*) controller;
        friendsController.isLoaded = NO;
    }
    
    //处理动态
    nav = [self.tabBarController.viewControllers objectAtIndex:1];
    [nav popToRootViewControllerAnimated:NO];
    
    controller = [nav.viewControllers objectAtIndex:0];
    if ( [controller isKindOfClass:[FriendsTimelineController class]] ) {
        FriendsTimelineController* tweetController = (FriendsTimelineController*) controller;
        tweetController.isLoaded = NO;
    }
    else {
        FriendsTimelineController* tweetController = [[FriendsTimelineController alloc] init];
        [nav setViewControllers:[NSArray arrayWithObject:tweetController]];
        [tweetController release];
    }
    
    
    //处理消息
    nav = [self.tabBarController.viewControllers objectAtIndex:2];
    [nav popToRootViewControllerAnimated:NO];
    
    controller = [nav.viewControllers objectAtIndex:0];
    if ( [controller isKindOfClass:[DMTimelineController class]] ) {
        DMTimelineController* dmController = (DMTimelineController*) controller;
        dmController.isLoaded = NO;
    }
}


- (void) clearUserData
{
    char* sql = "delete from statuses";
    [DBConnection execute:sql];
    
    sql = "delete from contact_statuses";
    [DBConnection execute:sql];
    
    sql = "delete from direct_messages";
    [DBConnection execute:sql];
    
    sql = "delete from followees";
    [DBConnection execute:sql];
    
    sql = "delete from operation_log";
    [DBConnection execute:sql];
}


#pragma mark - refresh methods

- (void) refreshFriendsTimeline
{
    UINavigationController* nav = [self.tabBarController.viewControllers objectAtIndex:1];
    for ( UIViewController* controller in nav.viewControllers ) {
        if ( [controller isKindOfClass:[FriendsTimelineController class]] ) {
            FriendsTimelineController* tweetController = (FriendsTimelineController*) controller;
            if ( tweetController.isRoot ) {
                tweetController.isLoaded = NO;
            }
        }
    }
    
}


#pragma mark - tool methods

NSInteger sortByScreenName( id a, id b, void *context )
{
    User* userA = (User*)a;
    User* userB = (User*)b;
    
    NSString* pyA = userA.pyLetters;
    NSString* pyB = userB.pyLetters;
    
    return [pyA compare:pyB];
}




@end

